package eai.tp2.lpco.purchase;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import eai.tp2.lpco.database.DigitalCamera;
import eai.tp2.lpco.database.Order;
import eai.tp2.lpco.database.User;
import eai.tp2.lpco.database.Order.Status;
import eai.tp2.lpco.wsclients.shippingdepartment.ShippingDepartmentService;

/**
 * Session Bean implementation class Purchasemanager
 */
@Stateless
public class PurchaseBean implements IPurchase {

	@PersistenceContext(unitName = "myLpcoCatalogue")
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public PurchaseBean() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * Add order to the database
	 */
	@Override
	public Order addOrderToDataBase(List<String> cameras,
			String username) {
		int amount = 0;
		List<DigitalCamera> cams = new ArrayList<DigitalCamera>();
		for (String name : cameras) {
			DigitalCamera temp = (DigitalCamera)em.createQuery("select c from DigitalCamera c where modelName = '"	+ name + "'").getSingleResult();
			amount += temp.getPrice();
			cams.add(temp);
		}
		User user = (User) em.createQuery(
				"select u from User u where u.username ='" + username + "'")
				.getSingleResult();
		Order order = new Order(user, new Date(), Status.PENDING);
		order.setDigitalCameras(cams);
		order.setAmount(amount);
		order.setUser(user);
		user.getOrders().add(order);	
		em.persist(order);				
		em.flush();
		ShippingDepartmentService ww  = new ShippingDepartmentService();
		ww.getShippingDepartmentPort().startShipping(order.getOrderId());		
		return order;
	}

	/**
	 * Verify User money
	 * 
	 */
	@Override
	public boolean hasMoney() {

		Random r = new Random();

		int num = r.nextInt(101);

		return num > 75 ? false : true;
	}

	/**
	 * Make the order as Delivered
	 */
	@Override
	public boolean changeStatus(int orderId, Status status) {

		Order order = (Order) em.createQuery(
				"select o from Order o where o.orderId = " + orderId)
				.getSingleResult();

		order.setStatus(Status.DELIVERED);

		return true;
	}
}
